#from dateutil import parser
import Image
import os
import tempfile
import time
from django.forms.models import modelformset_factory
from django.http import HttpRequest
from django.http import HttpResponseRedirect
from django import forms
from django.shortcuts import render_to_response

from webmapper.geophotos import EXIF
from webmapper.geophotos import models

from webmapper.geophotos.forms import data_forms
from webmapper.geophotos.forms import photo_forms
from webmapper.geophotos.processors import importers

from webmapper import settings


def CreateFromUpload(request):
  if request.method == "POST":
    message = "nothing"
    form = data_forms.DatasetForm(request.POST, request.FILES)
    if request.FILES.has_key('src_file'):
      src_file = request.FILES['src_file']
      message = "%s, %d" % (src_file.name, src_file.size)
      
      # Check existance of the dataset
      try:
        dataset = models.Dataset.objects.get(filename=src_file.name)
        return render_to_response('status.html',
                                  {'message': 'File exists.'})
      except Exception:
        dataset = models.Dataset()
        dataset.name = request.POST['name']
        if dataset.name == "":
          dataset.name = src_file.name
        dataset.filename = src_file.name
        
        dest_name = tempfile.mktemp(prefix="uploaded_",
            dir="%s/dataset" % settings.MEDIA_ROOT)
        dest_file = open(dest_name, 'wb+')
        for chunk in src_file.chunks():
          dest_file.write(chunk)
        dest_file.close()
        
        importer = importers.GpxImporter()
        importer.Import(dest_name)
      
        dataset.save()
        message = "File saved."
        return HttpResponseRedirect('/dataview/%s' % dataset.id)
    else:
      message = "form not valid"
    message = "Shapefile imported."
    return render_to_response('status.html',
                              {'message': message})
      
  elif request.method == "GET":
    datasets = models.Dataset.objects.all()
    form = data_forms.DatasetForm()
    return render_to_response('dataset_list.html',
                              {'datasets': datasets,
                               'form': form})


def ViewDataset(request, dsid):
  if request.method == "GET":
    # Get photos
    try:
      ref_id = int(dsid)
      photos = models.GeoPhoto.objects.filter(dataset_ref=ref_id)
      photos = photos or []
      dataset = models.Dataset.objects.get(id=ref_id)
      print dataset
      # Show a form for upload
      photo_form = photo_forms.PhotoFormInline()
      return render_to_response('dataset_view.html',
                                {'dataset': dataset,
                                 'photos': photos,
                                 'photo_form':photo_form})
    except Exception:
      return HttpResponseRedirect("/newdata/")
  elif request.method == "POST":
    photo_form = photo_forms.PhotoFormInline(request.POST, request.FILES)
    if request.FILES.has_key('media') and request.POST.has_key("dataset_id"):
      dataset = models.Dataset.objects.get(id=int(request.POST["dataset_id"]))
      
      photo_obj = models.GeoPhoto()
      photo_obj.dataset_ref = dataset
      
      src_file = request.FILES['media']
      src_ext = os.path.splitext(src_file.name)[-1]
      dest_name = tempfile.mktemp(suffix=src_ext, prefix="",
          dir="%s/photos" % settings.MEDIA_ROOT)
      dest_file = open(dest_name, 'wb+')
      for chunk in src_file.chunks():
        dest_file.write(chunk)
      dest_file.close()
      
      # Extract EXIF info
      f = open(dest_name, 'rb')
      tags = EXIF.process_file(f)
      t = time.strptime(str(tags['EXIF DateTimeOriginal']),
                        "%Y:%m:%d %H:%M:%S")
      photo_obj.time_taken = time.mktime(t)
      
      # Make thumbnails
      img = Image.open(dest_name)
      resize_ratio = img.size[1] / 60
      size = img.size[0] / resize_ratio, 60
      img.thumbnail(size)
      img.save("%s/thumbnails/%s" % (settings.MEDIA_ROOT,
               dest_name.split("/")[-1]))
      
      img = Image.open(dest_name)
      if img.size[1] > 360:
        resize_ratio = img.size[1] / 240
        size = img.size[0] / resize_ratio, 240
        img.thumbnail(size)
      img.save("%s/medium/%s" % (settings.MEDIA_ROOT,
               dest_name.split("/")[-1]))
     
      if request.POST.has_key("title"):
        photo_obj.title = request.POST["title"]
      else:
        photo_obj.title = src_file.name
        
      photo_obj.url = dest_name.split("/")[-1]
      
      photo_obj.save()
      return HttpResponseRedirect('/dataview/%s' % request.POST["dataset_id"])
    else: # return the form
      return render_to_response('status.html', {'message': 'form invalid'})


def FetchJSON(request, dsid):
  """Get Track data as JSON."""
  try:
    track_points = models.TrackPoint.objects.filter(track_ref=int(dsid)).order_by('timestamp')
    return render_to_response('track_points.json',
                              {'track_points': track_points})
  except Exception, s:
    return render_to_response('status.html',
                              {'message': 'Error: %s (%s).'
                               % (s, dsid)})    
